package com.hmall.search.runner;

import com.hmall.common.PageBean;
import com.hmall.feign.client.ItemClient;
import com.hmall.item.pojo.Item;
import com.hmall.search.constants.ItemConstants;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;

import java.util.List;

//@Component //将类交给Spring软件管理
public class Mysql2Es implements ApplicationRunner {

    @Autowired
    ItemClient itemClient;
    //注入es核心对象
    @Autowired
    RestHighLevelClient client;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        //1. 先判断item索引库是否存在
        GetIndexRequest getIndexRequest = new GetIndexRequest("item");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);


        //2. 如果不存在，就创建索引库
        if (!exists) {
            //1. 创建索引请求对象
            CreateIndexRequest request = new CreateIndexRequest("item");
            //设置索引的字段类型
            request.source(ItemConstants.JSON, XContentType.JSON);

            //2. 执行请求对象
            client.indices().create(request, RequestOptions.DEFAULT);
        }


        //项目启动时执行（只执行一次）
        //1. 获取到mysql数据库中的数据（通过feign接口）
        PageBean<Item> pageBean = itemClient.queryItemByPage(1, 1000);
        List<Item> list = pageBean.getList();

        //2. 遍历集合，将每一个Item对象添加到es中
        for (Item item : list) {
            //1. 创建文档请求对象
            IndexRequest request = new IndexRequest("item");
            //设置索引的字段类型
            request.id(String.valueOf(item.getId()));
            request.source(JSON.toJSONString(item), XContentType.JSON);

            //2. 执行请求对象
            client.index(request, RequestOptions.DEFAULT);
        }
    }
}